<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2021/6/23
 * Time: 11:02
 */

namespace app\admin\library;


class View
{
    /**
     * 获取view内容
     * @param $project
     * @param $module
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function view($project, $module)
    {
        $module_model = new \app\admin\model\MwModule();
        $column_model = new \app\admin\model\MwColumn();
        $result = [];
        //获取主模块信息
        $info = $module_model->getModuleInfo($project, $module);

        //获取模块字段列表
        $module_column_list = $column_model->where('module_id', $info['id'])->select();
        $main_data = JsonAnalysis::viewCreate($module_column_list);
        $result = array_merge($result, $main_data);

        //存在关联模块则获取关联模块字段
        $relevance = json_decode($info['relation_condition'], true);
        if (!empty($relevance)) {
            $relation = self::relevance($relevance);
            $result = array_merge($result, $relation);
        }

        return $result;
    }

    /**
     * 获取关联模块字段内容
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function relevance($data)
    {
        $column_model = new \app\admin\model\MwColumn();
        $result = [];
        foreach ($data as $value) {
            //获取模块字段列表
            $module_column_list = $column_model->alias('c')
                ->join('fa_mw_module m', 'c.module_id=m.id', 'LEFT')
                ->field('c.*')
                ->where('m.table_name', $value['name'])
                ->select();
            if ($module_column_list) {
                $alias = $value['alias'] ?? $value['name'];
                $main_data = JsonAnalysis::viewCreate($module_column_list, $alias);
                $result = array_merge($result, $main_data);
            }
            if (!empty($value['relation'])) {
                $relation = self::relevance($value['relation']);
                $result = array_merge($result, $relation);
            }
        }

        return $result;
    }
}